package com.jsnider.timelineplanner;


import java.util.ArrayList;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TimeScreen extends Activity{

	final static String TASK_NUM = "com.jsnider.timelineplanner.TASK_NUM";
	public TextView mainTaskTextView;
	public TextView minTextView;
	public TextView secTextView;
	public TextView timerTrueTextView;
	
	//varibles for the timeline data
	public int num_task;
	public String type;
	public ArrayList<Event> tasks = new ArrayList<Event>();
	public int place;
	private SharedPreferences savedSearches;
	
	//varibles for the countdowntimer
	public boolean timerOn;
	public static CountDownTimer timer;
	public int factor = 1000 * 10; // 60 is normal
	public long millToFinish;
	
	//varibles for the alarm manager
	public static PendingIntent pi;
    public static BroadcastReceiver br;
    public static AlarmManager am;
    
    //varibles for alert dialogs
    AlertDialog.Builder nextTaskAlert;
    AlertDialog.Builder moreTimeAlert;
    public static AlertDialog nextTaskDia;
    public static AlertDialog moreTimeDialog;
    boolean nextTaskDiaUp;
    
    //varibles to keep track of the notification
    NotificationManager mNotificationManager;
    boolean notUp;
    
    
    //TODO: ad control varibles to make sure text views don't fire over each other
    //TODO: call finish() in the right places
    
    
	
	@Override
	public void onCreate(Bundle savedInstanceState) {	
	 		super.onCreate(savedInstanceState);
			setContentView(R.layout.time_screen);

			savedSearches = getSharedPreferences("tasks", MODE_PRIVATE);
			mainTaskTextView = (TextView) this.findViewById(R.id.mainTaskTextView);
			secTextView = (TextView) this.findViewById(R.id.secTextView);
			minTextView = (TextView) this.findViewById(R.id.minTextView);
			
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			notUp = false;
			nextTaskDiaUp = false;
			
			
			Bundle my_bundle = getIntent().getExtras();
			if(my_bundle != null){
			num_task = my_bundle.getInt(TASK_NUM);
			type = my_bundle.getString("TYPE");
			if(type.equals("CREATE")) {
				place = 0;
			} else if (type.equals("RESTART")) {
				//THEN DO DIFFERENT STUFF
				place = my_bundle.getInt("PLACE");
			}
				
			Event temp;
			String temp_str;
			String temp_array[];
			for (int index = 0; index < num_task; ++index)
			{
				temp_str = savedSearches.getString(index+"", null);
				temp_array = temp_str.split(":");
				temp = new Event(temp_array[0], 
						Integer.parseInt(temp_array[1]));
				tasks.add(temp);
			}
			timerOn=false;
			setup();
			
			if(type.equals("RESTART")) {
				nextTaskDialog(place);
			} else
				startTimer();
			
			
		}
	}
	
	@Override
	public void onRestart() {
		super.onRestart();
		if(notUp == true){
			mNotificationManager.cancelAll();
			notUp = false;
		}
		
	}
	
	 private void setup() {
		 
	      br = new BroadcastReceiver() {
	             @Override
	             public void onReceive(Context c, Intent i) {
	                    
	            	 	Toast.makeText(c, "Time finished!", Toast.LENGTH_LONG).show();
	            	 	minTextView.setText("Time is finished\n Click Done");
	            	 	
	            	 	
	                    timerOn = false;	
	                    
	                    //play sound
		   		    	Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		   		    	Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
		   		    	r.play();
		   		    	
		   		    	if(MyApplication.isActivityVisible() == false)	
		   		    		makeNot();
		   		    	else
			   		    	nextTaskDialog(place);
	                   }
	             };
	      registerReceiver(br, new IntentFilter("com.jsnider.timelineplanner") );
	      pi = PendingIntent.getBroadcast( this, 0, new Intent("com.jsnider.timelineplanner"),
	0 );
	      am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
	}
	 
	public void makeNot()
	{
		NotificationCompat.Builder mBuilder =
		        new NotificationCompat.Builder(this)
		        .setSmallIcon(R.drawable.ic_launcher)
		        .setContentTitle("Task Finished")
		        .setContentText("Timeline Planner");
		
		// Creates an explicit intent for an Activity in your app
		Intent resultIntent = new Intent(this, TimeScreen.class);
		Bundle b = new Bundle();
		b.putString("TYPE", "RESTART");
		b.putInt(TASK_NUM, tasks.size());
		b.putInt("PLACE", place);
		resultIntent.putExtras(b);
		
		// The stack builder object will contain an artificial back stack for the
		// started Activity.
		// This ensures that navigating backward from the Activity leads out of
		// your application to the Home screen.
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(TimeScreen.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
		        stackBuilder.getPendingIntent(
		            0,
		            PendingIntent.FLAG_UPDATE_CURRENT
		        );
		mBuilder.setContentIntent(resultPendingIntent);
		mBuilder.setAutoCancel(true);
		mNotificationManager =
		    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.
		mNotificationManager.notify(1, mBuilder.build());
		notUp = true;
		//TODO: maybe finish activity if it's like that
	
	}
	
	public void startTimer()
	{
		//get task, get time, increment place
		mainTaskTextView.setText(tasks.get(place).getTask());	
		long time = tasks.get(place).getTime() * factor;	//turn to 10000 for minutes
		place++;
		
		if(timer != null)
			timer.cancel();
		timer = new CountDownTimer(time, 1000) {

		     public void onTick(long millisUntilFinished) {
		    	 long time = (millisUntilFinished / factor) ;
		    	 secTextView.setVisibility(View.GONE);
		    	 secTextView.setText("For: " + millisUntilFinished / 1000 + " more secs");
		    	 if(time >= 1) {
		    		 if(time == 1)
		    			 minTextView.setText("For: " + time   + " more minute");
		    		 else
		    			 minTextView.setText("For: " + time   + " more minutes");
		    	 } else
		    		 minTextView.setText("For: " + millisUntilFinished / 1000 + " more seconds");
		    	 
		    	 millToFinish = millisUntilFinished;
		     }

		     public void onFinish() {
		    	 timer.cancel();
		    	 }
		  }.start();
		  am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 
				  time, pi );
	}
	
	public int lastTaskCheck(int place)
	{
		if(place < tasks.size())
			return 0;
		else if (place == tasks.size())
			return 1;
		else 
			return 0;
	}
	
	public void nextTaskDialog(int place) {
		int mode; // false is nextDialog, true is last dialog
		mode = lastTaskCheck(place);

		nextTaskAlert = new AlertDialog.Builder(TimeScreen.this);

		switch (mode) {
		case 1: // last task

			nextTaskAlert.setTitle("Finished");

			nextTaskAlert.setMessage("Are you finished with your last task");
			nextTaskAlert.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int button) {
							SharedPreferences.Editor preferencesEditor = savedSearches
									.edit();
							preferencesEditor.clear();
							preferencesEditor.commit();

							// TODO: add congratulations screen
							Intent intent = new Intent(TimeScreen.this,
									MainActivity.class);
							startActivity(intent);

							finish();

						}
					});

			nextTaskAlert.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int button) {
							addMoreTime();
						}
					});

			nextTaskAlert.setCancelable(true);

			break;
		case 0:   // next task
			nextTaskAlert.setTitle("Finished");

			nextTaskAlert.setMessage("Are you ready to move onto your next task?");
			nextTaskAlert.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int button) {
							startTimer();
						}
					});

			nextTaskAlert.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int button) {
							addMoreTime();

						}
					});

			break;
		}
		nextTaskDia = nextTaskAlert.create();
		nextTaskDia.setOnDismissListener(new OnDismissListener() {
				public void onDismiss(final DialogInterface dialog) {
 					nextTaskDiaUp = false;
				}	
			}
		);

		if (nextTaskDiaUp == false) {
			nextTaskDia.show();
			nextTaskDiaUp = true;
		}
	}
	
	public void addMoreTime()
	{
		final EditText moreTime =  new EditText(this);
		moreTime.setGravity(Gravity.CENTER);
		moreTime.setPadding(130, 0, 130, 0);
		
		moreTimeAlert = new AlertDialog.Builder(TimeScreen.this);

		moreTimeAlert.setTitle("More time?");
		moreTimeAlert.setMessage("How many more minutes do you need?");
		moreTimeAlert.setView(moreTime);
		moreTimeAlert.setNegativeButton("Nevermind", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int button)
			{			
				//TODO: check if at the end
				//TODO: kill timer before hand
				int mode; // false is nextDialog, true is last dialog
				mode = lastTaskCheck(place);
				switch(mode)
				{
				case 0: // next task
					startTimer();
					break;
				case 1:
					// last task
					// launch done dialog
					SharedPreferences.Editor preferencesEditor = savedSearches
							.edit();
					preferencesEditor.clear();
					preferencesEditor.commit();

					// TODO: add congratulations screen
					Intent intent = new Intent(TimeScreen.this,
							MainActivity.class);
					startActivity(intent);
					break;
					
				}	
			}
				}
					);
		moreTimeAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int button)
			{	
				String newTime = moreTime.getText().toString();
				int newTime_int;
				try {
					newTime_int = Integer.parseInt(newTime);
				} catch (NumberFormatException e) {
					Toast.makeText(TimeScreen.this, "Enter a valid number", Toast.LENGTH_LONG).show();
					addMoreTime();
		            return;
				}

				if(newTime_int < 1)
					newTime_int = 1;
				if(newTime_int > 60)
					newTime_int = 60;
					
				String curr_task = tasks.get(place - 1).getTask();
				
				Event temp;
				temp = new Event(curr_task, newTime_int);	
				tasks.add(temp);				
				
				startTimer();		
			}
				}
					);
		moreTimeAlert.setCancelable(true);

		moreTimeDialog = moreTimeAlert.create();
		if(moreTimeDialog.isShowing() == false)
			moreTimeDialog.show();
	}
	

	public void goToNext(View v)
	{
		//dismiss notification
		if(notUp == true){
			mNotificationManager.cancelAll();
			notUp = false;
		}
		nextTaskDialog(place);
	}
	
	@Override
    protected void onDestroy() {
		 super.onDestroy();
//		 if(am != null) {
//			 am.cancel(pi);
//			 unregisterReceiver(br);
//		 }
		 if(timer != null){
			 timer.cancel();
		 }
    }
	
	@Override
	protected void onResume() {
	  super.onResume();
	  MyApplication.activityResumed();
	}

	@Override
	protected void onPause() {
	  super.onPause();
	  MyApplication.activityPaused();
	}
	
	public static class MyApplication extends Application {

		  public static boolean isActivityVisible() {
		    return activityVisible;
		  }  

		  public static void activityResumed() {
		    activityVisible = true;
		  }

		  public static void activityPaused() {
		    activityVisible = false;
		  }

		  private static boolean activityVisible;
		}
	
}
	
//	@Override
//	public void onStop() {
//	    super.onStop();
//	    SharedPreferences.Editor preferencesEditor = savedSearches.edit();
//	    preferencesEditor.putLong("millToFinish", millToFinish);
//	    preferencesEditor.putInt("place", place-1);
//	    preferencesEditor.putInt("num_task", num_task);
//	    preferencesEditor.commit();
//	    timer.cancel();
//	    finish();
//	}
//	
//	@Override
//	public void onStart() {
//		super.onStart();
//		boolean restart_true;
//		restart_true = savedSearches.getBoolean("timelineInProgress", false);
//		if(restart_true) {
//			millToFinish = savedSearches.getLong("millToFinish", 0);
//			place = savedSearches.getInt("place", 0);
//			reStartTimer();
//		} else {
//			SharedPreferences.Editor preferencesEditor = savedSearches.edit();
//			preferencesEditor.putBoolean("inProgress", true);
//			preferencesEditor.commit();
//			startTimer();
//		}
//	}
//	@Override
//	public void onSaveInstanceState(Bundle savedInstanceState) {
//	  super.onSaveInstanceState(savedInstanceState);
//	  // Save UI state changes to the savedInstanceState.
//	  // This bundle will be passed to onCreate if the process is
//	  // killed and restarted.
//	  savedInstanceState.putLong("millToFinish", millToFinish);
//	  savedInstanceState.putInt("place", place);
//	  timer.cancel();
//	  timerOn = false;
//	  // etc.
//	}
//	
//	@Override
//	public void onRestoreInstanceState(Bundle savedInstanceState) {
//	  super.onRestoreInstanceState(savedInstanceState);
//	  // Restore UI state from the savedInstanceState.
//	  // This bundle has also been passed to onCreate.
//	  millToFinish = savedInstanceState.getLong("millToFinish");
//	  place = savedInstanceState.getInt("place");
//	  reStartTimer();
//	}
 
	